package com.liu.stockmarket.ui.self

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.liu.stockmarket.BaseFragment
import com.liu.stockmarket.MainViewModel
import com.liu.stockmarket.StockMarketApplication
import com.liu.stockmarket.databinding.FragmentSelfBinding
import com.liu.stockmarket.databinding.HeaderCompositeIndexBinding
import com.liu.stockmarket.model.Stock
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.ui.kline.KlineActivity
import com.liu.stockmarket.ui.search.SearchResultAdapter
import com.liu.stockmarket.ui.stock.add.StockAddActivity
import com.liu.stockmarket.utils.confirm
import com.liu.stockmarket.utils.getKlineCode
import com.liu.stockmarket.utils.getKlineType
import com.liu.stockmarket.utils.toast
import com.lxj.xpopup.XPopup
import java.math.BigDecimal

class SelfFragment : BaseFragment() {

    private lateinit var viewModel: SelfViewModel

    private var _binding: FragmentSelfBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private lateinit var header: HeaderCompositeIndexBinding

    private lateinit var mAdapter: SelfAdapter
    private lateinit var mHeaderAdapter: HeaderAdapter

    private lateinit var selfStocks: List<StockEntity>

    private val mainViewModel: MainViewModel by activityViewModels()

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        val stockMarketApplication = this.requireActivity().application as StockMarketApplication

        viewModel = ViewModelProvider(
            this,
            SelfViewModel.SelfViewModeFactory(
                stockRepository = stockMarketApplication.stockRepository,
                easyMoneyRepository = stockMarketApplication.easyMoneyRepository
            )
        ).get(SelfViewModel::class.java)

        _binding = FragmentSelfBinding.inflate(inflater, container, false)
        header = HeaderCompositeIndexBinding.inflate(inflater, container, false)

        mAdapter = SelfAdapter()

        mAdapter.addHeaderView(header.root)
        mHeaderAdapter = HeaderAdapter()
        with(binding.rvList) {
            adapter = mAdapter
        }

        with(header.list) {
            this.layoutManager = LinearLayoutManager(
                this@SelfFragment.requireContext(),
                LinearLayoutManager.HORIZONTAL, false
            )
            adapter = mHeaderAdapter
        }
        binding.refreshLayout.setColorSchemeColors(Color.argb(100, 255, 152, 0))

        return binding.root


    }

    override fun listener() {
        binding.refreshLayout.setOnRefreshListener {
            viewModel.queryNowPrice(selfStocks)
        }
        mAdapter.setOnItemLongClickListener { adapter, _, position ->
            val item = adapter.getItem(position) as SelfAdapter.Item
            XPopup.Builder(this.requireContext())
                .asBottomList("操作", listOf("交易", "删除").toTypedArray()) { index, _ ->
                    when (index) {
                        0 -> {
                            StockAddActivity.start(
                                this.requireContext(), item = SearchResultAdapter.Item(
                                    code = item.code,
                                    name = item.name,
                                    stockType = item.stockType!!,
                                    type = "",
                                    transactionExchange = item.type!!,
                                )
                            )
                        }
                        1 -> {
                            this.requireContext().confirm("删除自选", "是否删除 ${item.name}", {
                                item.selfId?.let {
                                    viewModel.deleteSelf(it)
                                }

                            })
                        }
                        else -> {

                        }
                    }
                }.show()



            true
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as SelfAdapter.Item
            KlineActivity.start(
                requireContext(),
                item.code.getKlineCode(item.stockType!!, item.type!!),
                item.name,
                item.type.getKlineType()
            )
        }
        mHeaderAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as SelfAdapter.Item
            KlineActivity.start(
                requireContext(),
                if (item.code.startsWith("0")) {
                    "1.${item.code}"
                } else {
                    "0.${item.code}"
                },
                item.name,
                "hs"
            )
        }
        binding.rvList.setOnScrollChangeListener { _, _, scrollY, _, oldScrollY ->
            mainViewModel.setShowDataCenterButton(scrollY <= oldScrollY)
        }


    }


    override fun observer() {
        viewModel.allSelf.observe(this) {
            selfStocks = it
            binding.refreshLayout.isRefreshing = true
            viewModel.queryNowPrice(it)
        }
        viewModel.nowPrices.observe(this) {

            mAdapter.setList(it)

            binding.refreshLayout.isRefreshing = false
        }
        viewModel.compositeIndex.observe(this) {
            mHeaderAdapter.setList(it)
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        _binding = null

    }
}